package com.newflypig.jblog.dao.hibernate;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.newflypig.jblog.dao.ArticleDAO;
import com.newflypig.jblog.exception.JblogException;
import com.newflypig.jblog.model.Article;
import com.newflypig.jblog.model.Category;

@Repository("articleDao")
public class ArticleDAOImpl extends BaseHibernateDAO<Article> implements ArticleDAO{
	// property constants
	public static final String TEXT = "text";
	public static final String TITLE = "title";
	public static final String RATE = "rate";
	public static final String SUPPORT = "support";
	public static final String AGAINST = "against";
	
	@SuppressWarnings("unchecked")
	public List<Article> findAllDesc() {
		try {
			String queryString = "from Article order by articleId desc";
			Query queryObject = getSession().createQuery(queryString);
			List<Article> list=(List<Article>)queryObject.list();
			if(list.size()!=0)
				log.info("Find All Article objects order by articleId desc");
			else
				log.info("Find none Article object");
			return list;
		} catch (RuntimeException re) {
			log.error("Occur an Error when try to Find All Article objects", re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Article findById(Integer id) {
		try{
			//读取文章的基本数据字段
			String hql="select new Article(a.articleId,a.date,a.text,a.title,a.rate,a.support,a.against) from Article a where a.articleId=:id";
			Query query=this.getSession().createQuery(hql).setInteger("id", id);
			Article article=(Article)query.uniqueResult();
			if(article==null)
				throw new JblogException("The Article dosn't exsits!");
			
			//使用原生SQL读取文章的Category集合
			String sql="select c.* from category c join article_category ac on ac.category_id=c.category_id where ac.article_id=:id";			
			query=this.getSession().createSQLQuery(sql).addEntity(Category.class).setInteger("id", id);
			Set<Category> categories=new LinkedHashSet<Category>();
			categories.addAll(query.list());
			article.setCategories(categories);
			
			return article;
		}catch(RuntimeException re){
			log.error("Occer an Error when try to Find an Article Object,it's Id="+id);
			re.printStackTrace();
			throw re;
		}
	}
}